<template>
  <nav class="bg-transparent border-b border-transparent dark:bg-transparent dark:border-transparent w-full">
    <div class="w-full flex flex-wrap items-center justify-between">
      <a href="/" class="flex items-center mr-auto ">
        <!-- 网站标志 -->
        <img src="@/assets/weblog-logo-mini.png" class="h-10 w-30 mr-10px left-10 top-5" alt="Flowbite Logo" />
      </a>
      <div class="theme-toggle-wrapper">
        <ThemeToggle />
      </div>
      <div class="flex items-center md:order-2">
          <div class="flex mr-3">
            <button type="button"
              class="md:hidden text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:outline-none focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-2.5 mr-1"
              @click="openSearch"
              aria-label="搜索">
              <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 20 20">
                <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z" />
              </svg>
            </button>
            <!-- 桌面端搜索功能 -->
            <div class="relative hidden md:block transform -translate-x-25">
              <button 
                @click="openSearch" 
                class="p-2 text-gray-500 dark:text-gray-400
                 hover:bg-gray-100 dark:hover:bg-gray-700
                  rounded-lg focus:outline-none focus:ring-2
                  focus:ring-gray-200 dark:focus:ring-gray-600
                   transition-all duration-300"
              >
                <svg class="w-5 h-5" aria-hidden="true"
                  xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                  <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                    stroke-width="2" d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z" />
                  </svg>
                </button>
              </div>
                <button data-collapse-toggle="navbar-menu" type="button"
                  class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600"
                  aria-controls="navbar-menu" aria-expanded="false">
                  <span class="sr-only">Open main menu</span>
                  <svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none"
                    viewBox="0 0 17 14">
                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M1 1h15M1 7h15M1 13h15" />
                  </svg>
                </button>
                </div>
                <button v-if="isLogin == false" 
                  @click="$router.push('/login')" 
                  class="flex items-center justify-center w-12 h-12 rounded-full bg-white text-blue-600 hover:bg-blue-50 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700 transition-colors duration-300">
                  登录
                </button>
                <button type="button" v-else
                  class="flex mr-3 text-sm rounded-full md:mr-0 focus:ring-4 focus:ring-gray-300 dark:focus:ring-gray-600"
                  id="user-menu-button" aria-expanded="false" data-dropdown-toggle="user-dropdown"
                  data-dropdown-placement="bottom">
                          <span class="sr-only">Open user menu</span>
                          <!-- 用户登录头像 -->
                          <img class="w-10 h-10 rounded-full" :src="$store.state.setting.avatar" alt="user photo">
                      </button>

                      <div class="z-50 hidden my-4 text-base list-none bg-white divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 dark:divide-gray-600"
                      id="user-dropdown">
                      <ul class="py-2" aria-labelledby="user-menu-button">
                          <li>
                              <a @click="$router.push('/admin')"
                                  class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white">
                                  <svg class="inline w-3 h-3 mb-2px mr-1 text-gray-700 dark:text-white" aria-hidden="true"
                                      xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                          stroke-width="2"
                                          d="M10 14v4m-4 1h8M1 10h18M2 1h16a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1Z" />
                                  </svg>
                            进入后台
                              </a>
                          </li>
                          <li>
                              <a @click="logout"
                                  class="block px-4 py-2 text-rm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white cursor-pointer">
                                  <svg class="inline w-3 h-3 mb-2px mr-1 text-gray-700 dark:text-white" aria-hidden="true"
                                      xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16">
                                      <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                          stroke-width="2"
                                          d="M4 8h11m0 0-4-4m4 4-4 4m-5 3H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h3" />
                                  </svg>
                              退出登录
                              </a>
                          </li>
                      </ul>
                  </div>
                      </div>
                      <div class="items-center justify-between hidden w-full md:flex md:w-auto md:order-1" id="navbar-menu">
                          
                          <ul
                              class="flex flex-col p-4 md:p-0 mt-4 font-medium border border-transparent rounded-lg bg-transparent md:flex-row md:space-x-6 md:mt-0 md:border-0 md:bg-transparent dark:bg-transparent md:dark:bg-transparent dark:border-transparent">
                              <li>
                                  <a @click="$router.push('/')" 
                                 
                                      class="block py-2 px-3 text-2xl rounded md:bg-transparent md:p-0 md:dark:text-blue-500 " aria-current="page">
                                      <img src="@/assets/maozi.svg" alt="首页" class="inline-block mr-2 w-6 h-6 align-middle">
                                      首页
                                  </a>
                              </li>
                              <li>
                                  <a @click="$router.push('/category')"
                                    
                                      class="block py-2 px-3 text-2xl rounded hover:bg-transparent md:hover:bg-transparent  md: md:p-0 dark:text-white dark:hover:bg-transparent dark:hover:text-white md:dark:hover:bg-transparent dark:border-transparent">
                                       <img src="@/assets/fenlei.svg" alt="首页" class="inline-block mr-2 w-6 h-6 align-middle">
                                      分类
                                  </a>
                              </li>
                              <li>
                                  <a @click="$router.push('/tag')"
                                     
                                      class="block py-2 px-3 text-2xl
                                      rounded hover:bg-transparent md:hover:bg-transparent
                                       md: md:p-0 dark:text-white
                                      dark:hover:bg-transparent dark:hover:text-white md:dark:hover:bg-transparent
                                      dark:border-transparent">
                                       <img src="@/assets/biaoqian.svg" alt="首页" class="inline-block mr-2 w-6 h-6 align-middle">
                                      标签墙
                                  </a>
                              </li>

                              <li>
                                  <a @click="$router.push('/archive')"
                                     
                                      class="block py-2 px-3 text-2xl rounded hover:bg-transparent md:hover:bg-transparent  md: md:p-0 dark:text-white dark:hover:bg-transparent dark:hover:text-white md:dark:hover:bg-transparent dark:border-transparent">
                                       <img src="@/assets/guidang.svg" alt="归档" class="inline-block mr-2 w-6 h-6 align-middle">
                                      归档
                                  </a>
                              </li>

                              <li>
                                  <a @click="$router.push('/about')"
                                      class="block py-2 px-3 text-2xl rounded hover:bg-transparent md:hover:bg-transparent  md: md:p-0 dark:text-white dark:hover:bg-transparent dark:hover:text-white md:dark:hover:bg-transparent dark:border-transparent">
                                       <img src="@/assets/own.png" alt="关于我" class="inline-block mr-2 w-6 h-6 align-middle rounded-full">
                                      关于我
                                  </a>
                              </li>

                            <!-- 探索下拉菜单 -->
                            <li class="relative">
                              <el-dropdown placement="bottom-start">
                                      <span
                                          class="flex items-center py-2 px-3  rounded hover:bg-transparent 
                                          md:hover:bg-transparent 
                                          md:
                                           md:p-0 dark:text-white dark:hover:bg-transparent dark:hover:text-white
                                          md:dark:hover:bg-transparent dark:border-transparent cursor-pointer focus:outline-none">
                                          <img src="@/assets/tansuo.png" alt="探索" class="inline-block mr-2 w-9 h-9 align-middle">
                                         <div style="font-size:16px"> 探索</div>
                                          <el-icon class="el-icon--right ml-1">
                                              <arrow-down />
                                          </el-icon>
                                      </span>
                                <template #dropdown>
                                  <el-dropdown-menu class="min-w-[120px] border-0 shadow-lg">
                                    <el-dropdown-item class="text-base md:text-xl focus:outline-none hover:bg-transparent">
                                      <div @click="goToMessageWall"
                                           class="flex items-center rounded hover:bg-gray-100 dark:hover:bg-gray-600  dark:hover:text-blue-400 cursor-pointer px-4 py-2">
                                        <img src="@/assets/liuyanqiang.png" alt="留言墙" class="inline-block mr-2 w-6 h-6 align-middle">
                                        <span>留言墙</span>
                                      </div>
                                    </el-dropdown-item>
                                  </el-dropdown-menu>
                                </template>
                              </el-dropdown>
                            </li>
                          </ul>
                      </div>
          </div>
          </nav>

  <!-- 搜索遮罩层 -->
  <transition name="search-overlay">
    <div v-if="showSearchOverlay" class="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4" @click="handleOverlayClick">
      <!-- 搜索标题 -->
      <div class="absolute top-1/4 text-white text-3xl font-bold tracking-wide">
        文章搜索
      </div>
      
      <!-- 搜索输入框 -->
      <div class="w-full max-w-3xl" @click.stop>
        <div class="relative">
          <div class="absolute inset-y-0 left-0 flex items-center pl-6 pointer-events-none">
            <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-6-6m2-5a7 7 0 1 1-14 0 7 7 0 0 1 14 0Z"></path>
            </svg>
          </div>
          <input
            type="text" 
            class="block w-full py-6 pl-16 pr-6 text-xl bg-white/10 border border-white/20 rounded-full backdrop-blur-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-white/30 transition-all"
            placeholder="输入关键词搜索..."
            v-model="searchText"
            @input="performSearch"
            @keydown.enter="handleSearchSubmit"
            @keydown.esc="closeSearch"
            ref="searchInput"
          />
        </div>
        
        <!-- 搜索结果 -->
        <div v-if="searchResults.length > 0" class="mt-8 bg-white/5 backdrop-blur-sm rounded-xl p-6 max-h-96 overflow-y-auto">
          <div class="text-white mb-4 text-xl font-medium">搜索结果</div>
          <div class="space-y-4">
            <div 
              v-for="article in searchResults" 
              :key="article.id"
              @click="goToArticleDetail(article.id)"
              class="p-4 bg-white/5 hover:bg-white/10 rounded-lg transition-colors cursor-pointer"
            >
              <h3 class="text-white text-lg font-medium mb-2">{{ article.title }}</h3>
            </div>
          </div>
        </div>
        
        <!-- 无搜索结果提示 -->
        <div v-else-if="searchText.trim() && searchResults.length === 0" class="mt-8 bg-white/5 backdrop-blur-sm rounded-xl p-8 text-center">
          <p class="text-gray-300">未找到与 "{{ searchText }}" 相关的文章</p>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { showMessage } from '@/composables/util'
import { initDropdowns, initCollapses } from 'flowbite'
import ThemeToggle from './ThemeToggle.vue'
import { searchArticles } from '@/api/frontend/article'

const store = useStore()
const route = useRoute()
const router = useRouter()

const currPath = ref(route.path)
const keys = Object.keys(store.state.user)
const isLogin = ref(keys.length > 0)

// 搜索相关状态
const showSearchOverlay = ref(false)
const searchText = ref('')
const searchResults = ref([])
const searchInput = ref(null)
let searchTimeout = null

// 跳转到留言墙页面
const goToMessageWall = () => {
    router.push('/message-wall')
}

// 打开搜索功能
const openSearch = () => {
  showSearchOverlay.value = true
}

// 关闭搜索
const closeSearch = () => {
  searchText.value = ''
  searchResults.value = []
  showSearchOverlay.value = false
}

// 执行搜索
const performSearch = () => {
  if (searchText.value.trim() === '') {
    searchResults.value = []
    return
  }

  // 防抖处理
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    searchArticles(searchText.value)
      .then(response => {
        if (response.success) {
          searchResults.value = response.data || []
        }
      })
      .catch(error => {
        console.error('搜索文章失败:', error)
        searchResults.value = []
      })
  }, 300)
}

// 处理搜索提交
const handleSearchSubmit = () => {
  if (searchResults.value.length > 0) {
    goToArticleDetail(searchResults.value[0].id)
  }
}

// 跳转到文章详情页
const goToArticleDetail = (articleId) => {
  closeSearch()
  router.push({ path: '/article/detail', query: { articleId } })
}

// 处理遮罩层点击事件（点击空白部分关闭）
const handleOverlayClick = () => {
  closeSearch()
}

// 处理ESC键关闭
const handleEscKey = (event) => {
  if (event.key === 'Escape' && showSearchOverlay.value) {
    closeSearch()
  }
}

const logout = () => {
    console.log('登出')
    store.dispatch('logout')
    showMessage('退出登录成功', 'success')
    isLogin.value = false
}

// 定义组件事件
const emit = defineEmits([])

// 初始化组件
onMounted(() => {
  initCollapses();
  initDropdowns();
    
  // 添加全局事件监听
  document.addEventListener('keydown', handleEscKey)
  
  // 监听isVisible变化，当显示时聚焦输入框
  watch(() => showSearchOverlay.value, (newVal) => {
    if (newVal && searchInput.value) {
      setTimeout(() => {
        searchInput.value.focus()
      }, 100)
    }
  })
  
  // 监听路由变化
  const updateBackgroundOnRouteChange = () => {
    currPath.value = route.path
  }
  
  window.addEventListener('popstate', updateBackgroundOnRouteChange)
  
  // 组件卸载时取消监听
  onUnmounted(() => {
    window.removeEventListener('popstate', updateBackgroundOnRouteChange)
    document.removeEventListener('keydown', handleEscKey)
    if (searchTimeout) {
      clearTimeout(searchTimeout)
    }
  })
})
</script>

<style scoped>
.navbar-wrapper {
    height: 65px;
}

.logo-img {
    height: 45px;
}

.title {
    font-size: 1.8rem;
    font-weight: 800;
}

/* 确保导航栏在轮播图上方 */
nav {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

/* 胶囊式导航菜单样式 */
#navbar-menu {
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border-radius: 30px;
    padding: 0.25rem 1rem;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

/* 黑暗模式下的胶囊导航 */
.dark #navbar-menu {
    background-color: rgba(30, 30, 30, 0.9);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

/* 导航栏链接样式 */
#navbar-menu ul {
    display: flex;
    list-style: none;
    margin: 0;
    padding: 0;
    gap: 0.25rem;
}

/* 导航链接项样式 */
#navbar-menu li a,
#navbar-menu .el-dropdown {
    display: flex;
    align-items: center;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.95rem;
    font-weight: 500;
    color: #333;
    text-decoration: none;
    transition: all 0.3s ease;
}

.dark #navbar-menu li a,
.dark #navbar-menu .el-dropdown {
    color: #e0e0e0;
}

/* 导航链接悬停效果 */
#navbar-menu li a:hover,
#navbar-menu .el-dropdown:hover {
    background-color: rgba(0, 0, 0, 0.05);
    transform: translateY(-1px);
    color: #0066cc;
}

.dark #navbar-menu li a:hover,
.dark #navbar-menu .el-dropdown:hover {
    background-color: rgba(255, 255, 255, 0.05);
    color: #4dabf7;
}

/* 活跃导航链接样式 */
#navbar-menu li a.router-link-active,
#navbar-menu li a.active {
    background-color: #0066cc;
    color: white;
    box-shadow: 0 2px 8px rgba(0, 102, 204, 0.3);
}

.dark #navbar-menu li a.router-link-active,
.dark #navbar-menu li a.active {
    background-color: #4dabf7;
    color: #0f172a;
    box-shadow: 0 2px 8px rgba(77, 171, 247, 0.3);
}

/* 针对移动设备的导航样式 */
@media (max-width: 768px) {
    #navbar-menu {
        position: static !important;
        transform: none !important;
        width: 100%;
        margin-top: 0.5rem;
        background-color: rgba(255, 255, 255, 0.95);
    }
    
    .dark #navbar-menu {
        background-color: rgba(30, 30, 30, 0.95);
    }
    
    /* 移动端导航项垂直排列 */
    #navbar-menu ul {
        flex-direction: column;
        gap: 0.25rem;
    }
    
    /* 移动端菜单按钮定位 */
    button[data-collapse-toggle="navbar-menu"] {
        margin-left: auto;
    }
}

/* 滑动式胶囊主题切换按钮样式 */
#theme-toggle {
    transition: all 0.3s ease;
}

/* 主题切换容器样式 */
.theme-toggle-wrapper {
    display: flex;
    align-items: center;
    margin-right: 200px;
    z-index: 999;
    pointer-events: auto;
}

header nav * {
    pointer-events: auto !important;
}

/* 用户头像与搜索框间距 */
#user-menu-button {
  margin-right: 10px;
}

/* 确保搜索、主题、登录按钮样式和位置不变 */
/* 搜索按钮样式 */
#search-button {
    background: none;
    border: none;
    color: inherit;
    cursor: pointer;
    padding: 0.5rem;
    border-radius: 50%;
    transition: background-color 0.3s ease;
}

#search-button:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.dark #search-button:hover {
    background-color: rgba(255, 255, 255, 0.1);
}

/* 使胶囊按钮和导航链接居中显示 */
@media (min-width: 769px) {
  nav > div:first-child {
    display: flex;
    justify-content: space-between;
    position: relative;
    align-items: center;
    height: 100%;
  }
  
  #navbar-menu {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: auto;
    margin: 0;
  }
}

/* 确保导航栏始终位于页面上方 */
nav {
    position: fixed !important;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100 !important;
    transition: background-color 0.3s ease;
}

/* 页面内容下移，避免被固定导航栏遮挡 */
body {
    padding-top: 70px;
}

/* 下拉菜单样式适配 */
#navbar-menu .el-dropdown-menu {
    background-color: white;
    border-radius: 12px;
    border: none;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.dark #navbar-menu .el-dropdown-menu {
    background-color: #1e293b;
}

#navbar-menu .el-dropdown-item {
    padding: 0.75rem 1.5rem;
    transition: background-color 0.2s ease;
}

#navbar-menu .el-dropdown-item:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

.dark #navbar-menu .el-dropdown-item:hover {
    background-color: rgba(255, 255, 255, 0.05);
}

/* 下拉箭头样式 */
.el-dropdown .el-icon-arrow-down {
    transition: transform 0.3s ease;
}

.el-dropdown:hover .el-icon-arrow-down {
    transform: rotate(180deg);
}

/* 遮罩层过渡动画 */
.search-overlay-enter-active,
.search-overlay-leave-active {
  transition: opacity 0.3s ease;
}

.search-overlay-enter-from,
.search-overlay-leave-to {
  opacity: 0;
}

/* 搜索结果滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .text-3xl {
    font-size: 2xl;
  }
  
  .text-xl {
    font-size: lg;
  }
  
  .py-6 {
    padding-top: 1rem;
    padding-bottom: 1rem;
  }
  
  .max-h-96 {
    max-height: 20rem;
  }
  
  /* 移动端胶囊导航调整 */
  #navbar-menu {
    border-radius: 16px;
  }
  
  #navbar-menu li a,
  #navbar-menu .el-dropdown {
    padding: 0.75rem 1rem;
    border-radius: 12px;
  }
}
</style>